<template>
  <div class="service-records-container">
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleFilter"
          />
        </el-form-item>
        <el-form-item label="服务状态">
          <el-select v-model="filterForm.status" placeholder="选择状态" @change="handleFilter">
            <el-option label="全部" value="" />
            <el-option label="进行中" value="ongoing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="records-list">
      <el-timeline>
        <el-timeline-item
          v-for="record in serviceRecords"
          :key="record.id"
          :timestamp="record.date"
          :type="getStatusType(record.status)"
        >
          <el-card class="record-card">
            <template #header>
              <div class="record-header">
                <div class="left">
                  <span class="order-no">订单号：{{ record.orderNo }}</span>
                  <el-tag :type="getStatusType(record.status)">
                    {{ getStatusText(record.status) }}
                  </el-tag>
                </div>
                <div class="right">
                  <el-button 
                    v-if="record.status === 'ongoing'"
                    type="primary" 
                    size="small"
                    @click="handleAddLog(record)"
                  >
                    添加记录
                  </el-button>
                  <el-button 
                    type="primary" 
                    link
                    @click="handleViewDetail(record)"
                  >
                    查看详情
                  </el-button>
                </div>
              </div>
            </template>

            <div class="service-info">
              <div class="info-row">
                <span class="label">患者姓名：</span>
                <span>{{ record.patientName }}</span>
              </div>
              <div class="info-row">
                <span class="label">服务类型：</span>
                <span>{{ record.serviceType }}</span>
              </div>
              <div class="info-row">
                <span class="label">服务地点：</span>
                <span>{{ record.hospital }} {{ record.department }}</span>
              </div>
            </div>

            <div v-if="record.serviceLogs?.length" class="service-logs">
              <div v-for="log in record.serviceLogs" :key="log.id" class="log-item">
                <div class="log-time">{{ log.time }}</div>
                <div class="log-content">
                  <p>{{ log.content }}</p>
                  <div v-if="log.images?.length" class="log-images">
                    <el-image
                      v-for="img in log.images"
                      :key="img"
                      :src="img"
                      :preview-src-list="log.images"
                      fit="cover"
                      class="log-image"
                    />
                  </div>
                </div>
              </div>
            </div>

            <div v-if="record.evaluation" class="evaluation">
              <div class="eval-header">
                <span>患者评价</span>
                <el-rate
                  v-model="record.evaluation.rating"
                  disabled
                  show-score
                  text-color="#ff9900"
                />
              </div>
              <div class="eval-content">{{ record.evaluation.comment }}</div>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加服务记录对话框 -->
    <el-dialog
      v-model="logDialogVisible"
      title="添加服务记录"
      width="500px"
    >
      <el-form :model="logForm" :rules="logRules" ref="logFormRef" label-width="80px">
        <el-form-item label="记录内容" prop="content">
          <el-input
            v-model="logForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入服务过程记录"
          />
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload
            action="/api/upload"
            list-type="picture-card"
            :on-success="handleImageSuccess"
            :on-remove="handleImageRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="定位">
          <el-button type="primary" @click="getLocation">
            <el-icon><Location /></el-icon>
            获取当前位置
          </el-button>
          <div v-if="logForm.location" class="location-info">
            {{ logForm.location }}
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="logDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitLogForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 服务详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="服务详情"
      width="800px"
    >
      <div v-if="currentRecord" class="service-detail">
        <div class="detail-section">
          <h4>基本信息</h4>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">订单编号：</span>
              <span>{{ currentRecord.orderNo }}</span>
            </div>
            <div class="info-item">
              <span class="label">服务状态：</span>
              <el-tag :type="getStatusType(currentRecord.status)">
                {{ getStatusText(currentRecord.status) }}
              </el-tag>
            </div>
            <div class="info-item">
              <span class="label">患者姓名：</span>
              <span>{{ currentRecord.patientName }}</span>
            </div>
            <div class="info-item">
              <span class="label">联系电话：</span>
              <span>{{ currentRecord.patientPhone }}</span>
            </div>
            <div class="info-item">
              <span class="label">服务时间：</span>
              <span>{{ currentRecord.date }}</span>
            </div>
            <div class="info-item">
              <span class="label">服务地点：</span>
              <span>{{ currentRecord.hospital }} {{ currentRecord.department }}</span>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h4>服务记录</h4>
          <el-timeline>
            <el-timeline-item
              v-for="log in currentRecord.serviceLogs"
              :key="log.id"
              :timestamp="log.time"
              placement="top"
            >
              <p>{{ log.content }}</p>
              <div v-if="log.images?.length" class="log-images">
                <el-image
                  v-for="img in log.images"
                  :key="img"
                  :src="img"
                  :preview-src-list="log.images"
                  fit="cover"
                  class="log-image"
                />
              </div>
              <p v-if="log.location" class="location">
                <el-icon><Location /></el-icon>
                {{ log.location }}
              </p>
            </el-timeline-item>
          </el-timeline>
        </div>

        <div v-if="currentRecord.evaluation" class="detail-section">
          <h4>患者评价</h4>
          <div class="evaluation-detail">
            <div class="rating">
              <span class="label">评分：</span>
              <el-rate
                v-model="currentRecord.evaluation.rating"
                disabled
                show-score
                text-color="#ff9900"
              />
            </div>
            <div class="comment">
              <span class="label">评价内容：</span>
              <p>{{ currentRecord.evaluation.comment }}</p>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Location } from '@element-plus/icons-vue'

// 筛选表单
const filterForm = reactive({
  dateRange: [],
  status: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框显示控制
const logDialogVisible = ref(false)
const detailDialogVisible = ref(false)

// 当前选中的记录
const currentRecord = ref(null)

// 服务记录表单
const logForm = reactive({
  content: '',
  images: [],
  location: ''
})

// 表单验证规则
const logRules = {
  content: [
    { required: true, message: '请输入记录内容', trigger: 'blur' }
  ]
}

// 模拟数据
const serviceRecords = ref([
  {
    id: 1,
    orderNo: 'DD20240115001',
    status: 'completed',
    date: '2024-01-15',
    patientName: '张三',
    patientPhone: '13800138000',
    serviceType: '门诊陪诊',
    hospital: '协和医院',
    department: '内科',
    serviceLogs: [
      {
        id: 1,
        time: '09:30',
        content: '到达医院，开始排队挂号',
        location: '北京协和医院门诊大厅',
        images: []
      },
      {
        id: 2,
        time: '10:15',
        content: '完成挂号，等待就诊',
        location: '内科候诊区',
        images: []
      }
    ],
    evaluation: {
      rating: 5,
      comment: '服务很专业，态度很好'
    }
  }
])

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    ongoing: 'primary',
    completed: 'success',
    cancelled: 'info'
  }
  return typeMap[status]
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    ongoing: '进行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return textMap[status]
}

// 处理筛选
const handleFilter = () => {
  // TODO: 实现筛选逻辑
  console.log('筛选条件：', filterForm)
}

const resetFilter = () => {
  filterForm.dateRange = []
  filterForm.status = ''
  handleFilter()
}

// 添加服务记录
const handleAddLog = (record) => {
  currentRecord.value = record
  logForm.content = ''
  logForm.images = []
  logForm.location = ''
  logDialogVisible.value = true
}

// 查看详情
const handleViewDetail = (record) => {
  currentRecord.value = record
  detailDialogVisible.value = true
}

// 获取当前位置
const getLocation = () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      async (position) => {
        // TODO: 调用地理编码API获取位置描述
        logForm.location = '北京市海淀区XX街道'
        ElMessage.success('位置获取成功')
      },
      (error) => {
        ElMessage.error('位置获取失败')
      }
    )
  } else {
    ElMessage.error('浏览器不支持地理定位')
  }
}

// 处理图片上传
const handleImageSuccess = (response) => {
  logForm.images.push(response.url)
}

const handleImageRemove = (file) => {
  const index = logForm.images.indexOf(file.url)
  if (index !== -1) {
    logForm.images.splice(index, 1)
  }
}

// 提交服务记录
const submitLogForm = async () => {
  if (!logFormRef.value) return

  try {
    await logFormRef.value.validate()
    // TODO: 调用保存API
    
    if (currentRecord.value) {
      if (!currentRecord.value.serviceLogs) {
        currentRecord.value.serviceLogs = []
      }
      currentRecord.value.serviceLogs.push({
        id: Date.now(),
        time: new Date().toLocaleTimeString(),
        ...logForm
      })
    }
    
    ElMessage.success('服务记录添加成功')
    logDialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  // TODO: 重新加载数据
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // TODO: 重新加载数据
}

onMounted(() => {
  // TODO: 获取服务记录列表
})
</script>

<style scoped lang="scss">
.service-records-container {
  .filter-card {
    margin-bottom: 20px;
  }

  .records-list {
    .record-card {
      .record-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .left {
          display: flex;
          align-items: center;
          gap: 15px;

          .order-no {
            font-weight: bold;
          }
        }
      }

      .service-info {
        margin: 15px 0;

        .info-row {
          margin-bottom: 10px;
          display: flex;
          align-items: center;

          .label {
            width: 100px;
            color: #909399;
          }
        }
      }

      .service-logs {
        margin: 15px 0;
        padding: 15px;
        background: #f5f7fa;
        border-radius: 4px;

        .log-item {
          margin-bottom: 15px;

          &:last-child {
            margin-bottom: 0;
          }

          .log-time {
            font-size: 13px;
            color: #909399;
            margin-bottom: 5px;
          }

          .log-content {
            p {
              margin: 0 0 10px;
            }

            .log-images {
              display: flex;
              gap: 10px;
              margin-top: 10px;

              .log-image {
                width: 80px;
                height: 80px;
                border-radius: 4px;
              }
            }
          }
        }
      }

      .evaluation {
        margin-top: 15px;
        padding-top: 15px;
        border-top: 1px solid #ebeef5;

        .eval-header {
          display: flex;
          align-items: center;
          gap: 20px;
          margin-bottom: 10px;
        }

        .eval-content {
          color: #606266;
          font-size: 14px;
        }
      }
    }
  }

  .service-detail {
    .detail-section {
      margin-bottom: 30px;

      h4 {
        margin: 0 0 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #ebeef5;
      }

      .info-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;

        .info-item {
          display: flex;
          align-items: center;

          .label {
            width: 100px;
            color: #909399;
          }
        }
      }

      .evaluation-detail {
        .rating {
          margin-bottom: 15px;
        }

        .comment {
          .label {
            color: #909399;
          }

          p {
            margin: 10px 0 0;
            color: #606266;
          }
        }
      }
    }
  }

  .location-info {
    margin-top: 10px;
    color: #606266;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 